<template>
  <n-layout>
    <n-layout-header :bordered="true">
      <n-card :bordered="false" class="proCard" size="small">
        <BasicForm @register="register" @submit="handleSubmit">
        </BasicForm>
      </n-card>
    </n-layout-header>
    <n-layout-content>
      <!--      <n-space vertical>-->
      <!--        <n-space justify="left" align="center">
                <h6 style="font-size: x-large;font-weight: bold">概况</h6>
                <n-icon color="#52c41a" size="24">
                  <QuestionCircleFilled/>
                </n-icon>
                <n-statistic :tabular-nums=true>
                  <template #prefix>
                    <n-text>总量(IMEI):</n-text>
                  </template>
                  <n-number-animation ref="numberAnimationInstRef" :from="0" :to="totalCounts"/>
                </n-statistic>
              </n-space>-->
      <div id="trend_chart" ref="chartRef" style="height:640px;width:96%;">
        <!--        <n-space justify="end">-->
        <!--          <n-button type="info" @click="exportTable">导出</n-button>-->
        <!--        </n-space>-->
      </div>
      <!--      </n-space>-->
    </n-layout-content>
  </n-layout>


</template>

<script lang="ts" setup>
import {useRouter} from 'vue-router';
import {onMounted, Ref, ref} from "vue";
import {FormSchema, useForm} from "@/components/Form";
import {useECharts} from "@/hooks/web/useECharts";
import {useMessage} from "naive-ui";
import {nearlyDays, nearlyDay, formatdate} from "@/utils/dateUtil";
import {
  getProjectList,
  queryTotalCounts
} from "@/api/statistics/stastistics";
import {utils, writeFileXLSX} from 'xlsx'
import {QueryParamsStore} from "@/store/modules/queryParamsCache";

const router = useRouter();
const message = useMessage();

const chartRef = ref<HTMLDivElement | null>(null);
const {setOptions, getInstance, echarts} = useECharts(chartRef as Ref<HTMLDivElement>);

const dataRef = ref([] as any)
const loaderRef = ref(true)

const queryParamsStore = QueryParamsStore();

const queryParams = ref(queryParamsStore.getTrendParams)
const queryDate = ref<[string | null, string | null]>([queryParams.value.begin, queryParams.value.end]);

const lastTableColumns = [
  {
    title: '日期',
    key: 'date',
    align: 'center',
  },
  {
    title: '激活IMEI',
    key: 'counts',
    align: 'center',
  },
]

const schemas = ref<FormSchema[]>([
    {
      field: 'project',
      labelMessage: '项目名称',
      component: 'NSelect',
      label: '项目',
      defaultValue: queryParams.value.project,
      componentProps: {
        placeholder: '请选择项目',
        filterable: true,
        options: [],
        onUpdateValue: (e: any) => {
          queryParams.value.project = e;
        },
      },
    },
    {
      field: 'region',
      label: '时间段',
      labelMessage: '时间段',
      component: "NRadioButtonGroup",
      defaultValue: queryParams.value.days,
      componentProps: {
        placeholder: '请选择最近日期',
        filterable: true,
        options: [
          {
            label: '近7天',
            value: 7,
          },
          {
            label: '近30天',
            value: 30,
          },
        ],
        onUpdateValue: (e: any) => {
          queryParams.value.days = e;
          queryDate.value[0] = nearlyDays(e);
          queryDate.value[1] = nearlyDays(1);
          queryParams.value.begin = queryDate.value[0];
          queryParams.value.end = queryDate.value[1];
          schemas.value[2].componentProps!['formattedValue'] = queryDate;
        },
      },
    },
    {
      field: 'dateRange',
      component: 'NDatePicker',
      label: '日期范围',
      // defaultValue:[queryParams.value.begin,queryParams.value.end],
      componentProps: {
        placeholder: '请选择日期',
        type: 'daterange',
        formattedValue: queryDate,
        // clearable: true,
        onUpdateValue: (e: any, formattedValue: string) => {
          if (formattedValue != null) {
            queryParams.value.begin = formattedValue[0];
            queryParams.value.end = formattedValue[1];
            queryDate.value[0] = formattedValue[0];
            queryDate.value[1] = formattedValue[1];
          } else {
            queryDate.value[0] = nearlyDays(queryParams.value.days);
            queryDate.value[1] = nearlyDays(1);
            queryParams.value.begin = queryDate.value[0];
            queryParams.value.end = queryDate.value[1];
          }

        },
        shortcuts:
          {
            '近7天': [new Date(nearlyDays(7)).getTime(), new Date(nearlyDays(1)).getTime()] as const,
            '近30天': [new Date(nearlyDays(30)).getTime(), new Date(nearlyDays(1)).getTime()] as const,
          }
      },
    },
  ])
;

const [register, {}] = useForm({
  gridProps: {
    // xGap: "5",
    // yGap: "8",
    cols: '1  m:1 l:3',
    // collapsed:true,
    collapsedRows: 3,
    // cols: '3'
  },
  // layout: 'horizontal',
  showAdvancedButton: false,
  showResetButton: false,
  labelWidth: 80,
  schemas,
});


function updateChart(xAxisData: [], legendData: [], seriesData: [], total = 0, sum = 0) {
  setOptions({
    tooltip: {
      trigger: 'axis',
      show: true,
      /* formatter:(v)=>{
         console.log(v);
         return v;
       },*/
      axisPointer: {
        lineStyle: {
          width: 1,
          color: '#019680',
        },
      },
    },
    toolbox: {
      feature: {
        saveAsImage: {},
        myTool: {
          show: true,
          title: '导出数据',
          icon: 'image://icon_excel.svg',
          onclick: exportTable
        },
        dataView: {}
      }
    },
    title: {
      text: `概况{icon|}总量(IMEI):${total}`,
      subtext: `时间段内总量(IMEI):${sum}`,
      textStyle: {
        rich: {
          icon: {
            width: 24,
            height: 24,
            color: "rgb(0,120,0)",
            backgroundColor: {
              image: 'help.svg'
            }
          }
        }
      }
    },

    legend: {
      orient: 'horizontal',
      top: 'bottom',
      data: legendData
    },
    grid: {left: '5%', right: '5%', top: '15%', bottom: '20%', containLabel: true},
    xAxis: {
      name: '日期(日)',
      type: 'category',
      splitNumber: queryParams.value.days,
      data: xAxisData,
      axisLabel: {
        interval: 0,
        color: (v) => {
          return (parseInt(formatdate(v)) % 2 == 0) ? 'CadetBlue' : 'black';
        },
        formatter: (v) => {
          return formatdate(v);
        },
      }
    },
    yAxis: {
      name: '激活数量',
      type: 'value',
      // max: 10000,
      splitNumber: 10,
    },
    series: seriesData,
  });
}

function fillDays(days = 7) {
  const titles = [] as any;
  for (let i = days; i > 0; i--) {
    titles.push(nearlyDay(i));
  }
  return titles;
}

onMounted(async () => {
  const projectList = await getProjectList();
  const projects = [] as any;
  projectList.forEach((e: any) => {
    projects.push({label: e['name'], value: e['id']});
  });
  schemas.value[0].componentProps!['options'] = projects;
  schemas.value[0].defaultValue = queryParams.value.project;
  await getLastDays();
});

async function getLastDays() {
  const barChar = getInstance();
  barChar?.showLoading();
  loaderRef.value = true;
  const {list} = await queryParamsStore.queryProjectCounts({...queryParams.value});
  const {total} = await queryTotalCounts({});
  dataRef.value = list;
  const titles = fillDays(queryParams.value.days);
  const series_list = ref([] as any);
  const projects = ref({});
  let subTotal = 0;
  for (const {project, date, count} of list) {
    const index = titles.indexOf(date);
    let item;
    if (projects.value.hasOwnProperty(project)) {
      item = projects.value[project];
    } else {
      const data_list: number[] = new Array(queryParams.value.days);
      data_list.fill(0, 0)
      item = {
        name: project,
        type: 'line',
        // stack: 'Total',
        // stack: 'x',
        smooth: true,
        data: data_list,
        label: {
          show: true
        }
      };
      projects.value[project] = item;
    }
    item.data[index] = count;
    subTotal += count;
    // console.log(`${project}${date},${count}`);
  }
  const legend_data = [] as any;
  for (let key in projects.value) {
    legend_data.push(key);
    series_list.value.push(projects.value[key])
  }
  // console.log(series_list)
  // console.log(legend_data)
  updateChart(titles, legend_data, series_list, total, subTotal);
  barChar?.hideLoading();
  loaderRef.value = false;
}

function handleSubmit() {
  getLastDays();
}

function exportTable() {
  // const workBook = utils.table_to_book(document.getElementById("trend_chart"));
  const workBook = utils.book_new();
  const ws = utils.json_to_sheet(dataRef.value);
  utils.book_append_sheet(workBook, ws, "时间段数据");
  try {
    writeFileXLSX(workBook, "项目出货统计.xlsx");
    message.success("导出成功");
  } catch (e) {
    message.error("导出失败");
  }
}
</script>

<style lang="less" scoped>
.page-container {
  width: 100%;
  border-radius: 4px;
  padding: 50px 0;
  height: 100vh;

  .text-center {
    h1 {
      color: #666;
      padding: 20px 0;
    }
  }

  img {
    width: 350px;
    margin: 0 auto;
  }
}
</style>
